# coding=utf-8
# author:ylf
# contact: ylf8708@126.com
# datetime:2021/5/30 20:53

"""
文件说明：
每周买卖策略（根据周一买，周四卖的策略进行选股，并剔除掉不正常的交易信号，同时进行交易信号的整合）
"""

import data.stock as st
import strategy.base as base
import matplotlib.pyplot as plt
import numpy as np
import datetime


def week_period_strategy(code, starttime, end_time, freq):
    """
    周期交易策略
    :param code:股票代码
    :param starttime: 开始时间
    :param end_time: 结束时间
    :param freq: 频率
    :return:dataframe
    """
    # 获取股票数据
    data = st.get_single_stock(
        code=code,
        startdate=starttime,
        enddate=end_time,
        per_fre=freq)
    # 为dataframe添加week_day列，更加直观
    data['week_day'] = data.index.weekday
    # 周一设置买入信号
    # np的筛选写法
    data['buy_signal'] = np.where((data['week_day'] == 0), 1, 0)
    # 周四设置卖出信号
    data['sell_signal'] = np.where((data['week_day'] == 3), -1, 0)
    # 整合信号
    data = base.conform_signal(data)
    # 计算单次收益率
    data = base.calculate_return_rate(data)
    # 计算累计收益率
    data = base.calculate_sum_rate(data)
    return data


def mooc_task():
    data1 = week_period_strategy('000607.XSHE', '2018-01-01', datetime.date.today(), 'daily')
    data2 = week_period_strategy('000001.XSHE', '2018-01-01', datetime.date.today(), 'daily')
    data3 = week_period_strategy('000008.XSHE', '2018-01-01', datetime.date.today(), 'daily')
    # 合并累计收益率进同一个dataframe





if __name__ == '__main__':
    # current_data = week_period_strategy('000607.XSHE', None, datetime.date.today(), 'daily')
    # dataframe的筛选写法
    # print(current_data[['close', 'singal', 'sum_rate']])
    # plt.plot(current_data[['sum_rate']])
    # plt.show()

    # 计算最大回撤
    # test_data = st.get_single_stock(code='000607.XSHE', startdate='2021-07-01', enddate=datetime.date.today(), per_fre='daily')
    # df = base.calculate_max_drawdown(test_data)
    # df = df[['close', 'rolling_max', 'max_dd_daily', 'max_dd']]
    # print(df)
    # plt.plot(df)
    # plt.show()

    # 计算夏普比率
    test_data = st.get_single_stock(code='000607.XSHE', startdate='2020-07-25', enddate=datetime.date.today(), per_fre='daily')
    sharp_data = base.calculate_sharpe_rate(test_data)
    print(sharp_data)
